package com.castile.secondkill.controller;

import com.castile.secondkill.error.EmBusinessError;
import com.castile.secondkill.exception.BusinessException;
import com.castile.secondkill.response.CommonResponse;
import com.castile.secondkill.service.UserService;
import com.castile.secondkill.service.model.UserModel;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import sun.misc.BASE64Encoder;

import javax.servlet.http.HttpServletRequest;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Random;

/**
 * @author Hongliang Zhu
 * @create 2023-03-05 20:47
 */
@RestController
@RequestMapping("/user")
public class UserController extends BaseController{
    private static final Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private UserService userService;

    @Autowired
    private HttpServletRequest httpServletRequest;


    @PostMapping("/login")
    @ResponseBody
    public CommonResponse login(@RequestParam(name = "telephone") String telephone,
                                @RequestParam(name = "password") String password) throws BusinessException, NoSuchAlgorithmException {

        // 入参校验
        if (StringUtils.isEmpty(telephone) || StringUtils.isEmpty(password)) {
            throw new BusinessException(EmBusinessError.PARAMETER_VALIDATIONERROR);
        }

        // 调用登录服务，校验当前用户是否合法
        UserModel userModel = userService.validateLogin(telephone, EncodeByMD5(password));

        // 加入到用户登录成功的session内
        this.httpServletRequest.getSession().setAttribute("IS_LOGIN", true);
        this.httpServletRequest.getSession().setAttribute("LOGIN_USER", userModel);
        return CommonResponse.create(null);
    }

    /**
     * 用户注册接口
     *
     * @param telephone 手机号
     * @param otpCode   验证码
     * @param name      姓名
     * @param age       年龄
     * @param gender    性别
     * @param password  密码
     * @return 结果
     * @throws BusinessException
     * @throws NoSuchAlgorithmException
     */
    @RequestMapping(value = "/regist",  method = {RequestMethod.POST})
    @ResponseBody
    @Transactional
    public CommonResponse register(@RequestParam(name = "telephone") String telephone,
                                   @RequestParam(name = "otpCode") String otpCode,
                                   @RequestParam(name = "name") String name,
                                   @RequestParam(name = "age") Integer age,
                                   @RequestParam(name = "gender") Integer gender,
                                   @RequestParam(name = "password") String password) throws BusinessException, NoSuchAlgorithmException {

        logger.warn("用户：" +name +"前来注册啦！");
        // 首先就需要验证 校验码是否正确
        String inSessionOtpCode = (String) this.httpServletRequest.getSession().getAttribute(telephone);

        if (!StringUtils.equals(otpCode, inSessionOtpCode)) {
            throw new BusinessException(EmBusinessError.PARAMETER_VALIDATIONERROR, "短信验证码错误");
        }
        UserModel userModel = new UserModel();
        userModel.setAge(age);
        userModel.setGender(new Byte(String.valueOf(gender.intValue())));
        userModel.setName(name);
        userModel.setTelephone(telephone);
        userModel.setEncriptPassword(EncodeByMD5(password));
        userModel.setRegistMode("by phone");
        // 用户注册流程
        userService.register(userModel);
        return CommonResponse.create(null);
    }


    /**
     * 用户获取otp短信接口
     *
     * @param telephone 手机号
     * @return
     */
    @RequestMapping(value = "/getotp", method = {RequestMethod.POST})
    @ResponseBody
    public CommonResponse getOtp(@RequestParam("telephone") String telephone) {
        // 需要按照一定的规则去生成OTP验证码
        Random random = new Random();
        int randomInt = random.nextInt(99999);
        randomInt += 10000;
        String otpCode = String.valueOf(randomInt);
        // 将OTP验证码同对应用户的手机号关联  httpsession
        httpServletRequest.getSession().setAttribute(telephone, otpCode);
        // 将OTP验证码通过短信通道发送给用户： 省略
        System.out.println("telephone:" + telephone + "& otpCode:" + otpCode);
        return CommonResponse.create(null);
    }

    /**
     * md5加密
     *
     * @param str
     * @return
     * @throws NoSuchAlgorithmException
     */
    public String EncodeByMD5(String str) throws NoSuchAlgorithmException {
        // 确定计算方法
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        BASE64Encoder encoder = new BASE64Encoder();
        // 加密字符串
        String newStr = encoder.encode(md5.digest(str.getBytes()));
        return newStr;
    }
}
